var app = getApp()
var WxParse = require('../../wxParse/wxParse.js');
var video = require('../video-info/model/VideoModel.js')
var json = require('../../utils/json_helper.js')
var nlp = require('../../utils/nlp/LevenshTeinDistance.js')
var feedBack=require('../../pages/courseinfo/model/FeedBack.js')
var pay = require('../componet/pay/PayMentModel.js')
import SystemInfoUtil from '../../utils/SystemInfoUtil.js'
var bottomAnimation = wx.createAnimation({
  duration: 300,
  timingFunction: 'linear',
  height: 0,
  top: 0,
  bottom: 0,
  right: 0,
  backgroundColor: '#fff',
  opcity: 0.6
})
var color_selected = "#06d166"
var color_unselected = "#000000"
Page({
  data: {
    page: 1,
    size: 5,
    courseFree: 0,
    courseBuyFlag: 0,
    videoList: [],
    currentVideoNo: null,
    currentCourseNo: null,
    currentVideoInfo: {},
    currentResource: '',
    multiListShow: false,
    rateShow: false,
    currentRate: '1.0',
    videoPlaying: false,
    controlHidden: true,
    currentTime: 0,
    isSwitchDefinition: false,
    currentPoster: '',
    currentVideoTitle: '',
    currentVideoResource: [],
    currentDefinition: '',
    isAndroid: false,
    fullScreenData: "",
    currentTab: '0',
    showLoading: false,
    showNoMoreData: false,
    tuijian_text_color: color_selected,
    all_goods_text_color: color_unselected,
    introduce_text_color: color_unselected,
    hasSubject: false,
    subjectList: [],
    errorSubjectList: [],
    errRateValue: 0,
    okSubjectList: [],
    okRateValue: 70,
    optTip: '',
    swiper: {
      active: 0
    },
    subjectItemHeight: 35,
    swiperHeight: 100,
    currentSubjectPageIndex: 0,
    selectedAnswers: [],
    submitButtonShow: 'hidden',
    showModal: false,
    feedBackText:'',
    isIOS:false
  },
  //重制页面数据，主要是当前页面点击相关课程后重置相关数据
  reSetPageData() {
    this.setData({
      currentVideoNo: null,
      currentVideoInfo: {},
      currentPoster: '',
      currentVideoTitle: '',
      currentVideoResource: [],
      currentDefinition: '',
      hasSubject: false,
      subjectList: [],
      errorSubjectList: [],
      errRateValue: 0,
      okSubjectList: [],
      okRateValue: 0,
      optTip: '',
      swiper: {
        active: 0
      },
      subjectItemHeight: 35,
      swiperHeight: 100,
      currentSubjectPageIndex: 0,
      selectedAnswers: [],
      submitButtonShow: 'hidden',
      showModal: false,
      showResultTip: false,
      feedBackText: ''
    })
  },

  // 视频缓冲触发事件
  videoWaiting() {
    this.setData({
      controlHidden: true
    })
  },
  // 截获竖向滑动
  catchTouchMove: function(res) {
    return false
  },
  //swiper切换监听
  swiperChange: function(res) {

  },
  //动画结束
  swiperAnimationfinish: function(res) {
    this.setData({
      currentSubjectPageIndex: res.detail.current
    })
  },
  //上一题
  preSubject: function() {
    var that = this
    var _index = this.data.currentSubjectPageIndex - 1;
    if (_index <= 0) {
      _index = 0
    }
    this.setData({
      currentSubjectPageIndex: _index,
      submitButtonShow: (this.data.selectedAnswers.length == this.data.subjectList.length && this.data.showResultTip == false) ? 'show' : 'hidden'
    })
  },
  //下一题
  nextSubject: function() {
    var that = this
    var _index = that.data.currentSubjectPageIndex + 1;
    if (_index >= that.data.subjectList.length) {
      _index = that.data.subjectList.length - 1
    }
    that.setData({
      currentSubjectPageIndex: _index,
      submitButtonShow: (that.data.selectedAnswers.length == that.data.subjectList.length && that.data.showResultTip == false) ? 'show' : 'hidden'
    })
  },

  /**
   * 选择题选项
   */
  subjectSelectClick: function(event) {
    var args = event.currentTarget.dataset
    var subjectIndex = args.subjectindex
    var optionIndex = args.optionindex
    var _subjectNo = args.subjectid
    //正在进行的题目
    var makeSubejct = this.data.subjectList[subjectIndex];
    var updateField = 'subjectList[' + subjectIndex + '].option'
    var selectedAnswer = null
    makeSubejct.option.forEach(function(opt, index) {
      if (optionIndex == index) {
        selectedAnswer = opt
        opt['selectStatus'] = 1
      } else {
        opt['selectStatus'] = 0
      }
    })
    if (selectedAnswer == null) {
      return
    }
    //是否已经回答过
    var tmpAnswerList = this.data.selectedAnswers;
    var exitsAnswer = false
    tmpAnswerList.forEach(function(item, index) {
      if (item.subjectNo == _subjectNo) { //如果存在就修改该题的答案即可
        exitsAnswer = true
        item.subjectIndex = subjectIndex
        item.answer = selectedAnswer.key
      }
    })
    if (exitsAnswer == false) {
      //构造存储的已经选择答案
      var answer = {
        subjectIndex: subjectIndex,
        subjectNo: _subjectNo,
        answer: selectedAnswer.key,
        type: makeSubejct.type
      }
      tmpAnswerList.push(answer)
    }
    console.log("回答答案列表：%o", tmpAnswerList)
    this.setData({
      [updateField]: makeSubejct.option,
      selectedAnswers: tmpAnswerList,
      submitButtonShow: (this.data.selectedAnswers.length == this.data.subjectList.length && this.data.showResultTip == false) ? 'show' : 'hidden'
    })
  },
  /**
   * 填空题输入答案
   */
  inputBlur: function(event) {
    console.log(event)
    var args = event.currentTarget.dataset
    var subjectIndex = args.subjectindex
    var _optionIndex = args.optionindex
    var _subjectNo = args.subjectid
    var inputValue = event.detail.value
    var viewId = event.currentTarget.id
    var makeSubejct = this.data.subjectList[subjectIndex];
    var tmpAnswerList = this.data.selectedAnswers;
    //是否已经回答过
    var exitsAnswer = false
    var currentAnswerItem = null;
    var currentAnswerItemIndex = null;
    tmpAnswerList.forEach(function(item, index) {
      if (item.subjectNo == _subjectNo) { //如果存在就修改该题的答案即可
        exitsAnswer = true
        currentAnswerItem = item
        currentAnswerItemIndex = index
      }
    })
    if (exitsAnswer) { //存在，修改
      var answers = currentAnswerItem.answer
      var isUpdateOrg = false
      answers.forEach(function(item, index) {
        if (item.id == viewId) { //修改原来的答案
          isUpdateOrg = true
          item.value = inputValue
        }
      })
      //答案数组原来没有，新增 一般出现在多个空中
      if (isUpdateOrg == false) {
        answers.push({
          id: viewId,
          optionindex: _optionIndex,
          value: inputValue
        })
      }
      currentAnswerItem.answer = answers
      var updateField = 'selectedAnswers[' + currentAnswerItemIndex + ']'
      this.setData({
        [updateField]: currentAnswerItem
      })
    } else { //不存在添加
      var answer = {
        subjectIndex: subjectIndex,
        subjectNo: _subjectNo,
        answer: [{
          id: viewId,
          optionindex: _optionIndex,
          value: inputValue
        }],
        type: makeSubejct.type
      }
      tmpAnswerList.push(answer)
    }
    console.log(tmpAnswerList)
    this.setData({
      selectedAnswers: tmpAnswerList,
      submitButtonShow: (this.data.selectedAnswers.length == this.data.subjectList.length && this.data.showResultTip == false) ? 'show' : 'hidden'
    })
  },

  answerInput: function(event) {

  },
  //批改题目
  correctionSubject: function(event) {
    console.log("开始批改...")
    // debugger
    wx.showLoading({
      title: '请稍后...',
    });
    var selectedAnswers = this.data.selectedAnswers;
    console.log("待批改答案:%o", selectedAnswers)
    var subjectList = this.data.subjectList;
    if (selectedAnswers.length != subjectList.length) {
      wx.showModal({
        title: '温馨提示',
        content: '还有题目未完成，请先完成所有练习！',
      })
      return
    }
    var errorSuject = []
    var okSubject = []
    selectedAnswers.forEach(function(inputAnswer, aIndex) {
      subjectList.forEach(function(subject, sIndex) {
        if (inputAnswer.subjectNo == subject.id) {
          var answerType = subject.type
          if (answerType == 1) { //选择
            var answer1 = inputAnswer.answer.toLowerCase()
            var answer2 = subject.answer.toLowerCase()
            subject['subjectIndex'] = inputAnswer.subjectIndex
            subject['inputAnswer'] = inputAnswer.answer
            if (answer1 != answer2) {
              errorSuject.push(subject)
              subject['answerStatus'] = 0 //错误
            } else {
              subject['answerStatus'] = 1 //正确
              okSubject.push(subject)
            }
          } else if (answerType == 2) { //填空题
            var answerList = inputAnswer.answer
            var answerOkList = subject.answer
            var flag = true
            //题目答案多个空
            for (var i = 0; i < answerOkList.length; i++) {
              for (var j = 0; j < answerList.length; j++) {
                if (answerOkList[i].key == (answerList[j].optionindex + 1)) {
                  var answer1 = answerOkList[i].value.toLowerCase().replace(/[\ |\~|\`|\!|\@|\#|\$|\%|\^|\&|\*|\(|\)|\-|\_|\+|\=|\||\\|\[|\]|\{|\}|\;|\:|\"|\'|\,|\<|\.|\>|\/|\?]/g, "")
                  var answer2 = answerList[j].value.toLowerCase().replace(/[\ |\~|\`|\!|\@|\#|\$|\%|\^|\&|\*|\(|\)|\-|\_|\+|\=|\||\\|\[|\]|\{|\}|\;|\:|\"|\'|\,|\<|\.|\>|\/|\?]/g, "")
                  console.log("answer1=" + answer1 + ",answer2=" + answer2)
                  answerOkList[i]['inputAnswer'] = answerList[j].value
                  if (answer1 != answer2) {
                    //计算文本相似度得分>=0.6即可认为通过
                    var score = nlp.LevenshteinDistance.init(answer1, answer2).get()
                    console.log('相似度：' + score)
                    answerOkList[i]['score'] = score.toFixed(2)
                    if (score < 0.6) {
                      flag = false
                    }
                    break;
                  } else {
                    answerOkList[i]['score'] = 1
                  }
                }
              }
            }
            subject['subjectIndex'] = inputAnswer.subjectIndex
            subject.answer = answerOkList
            console.log("subject%o", subject)
            if (!flag) {
              subject['answerStatus'] = 0 //错误
              errorSuject.push(subject)
            } else {
              subject['answerStatus'] = 1 //错误
              okSubject.push(subject)
            }
          }

          return
        }
      })
    })
    // console.log("错题：%o", errorSuject)
    // console.log("对题：%o", okSubject)
    //计算正确率
    var errRate = errorSuject.length / subjectList.length
    var okRate = okSubject.length / subjectList.length

    console.log("错误率：" + Number(errRate * 100).toFixed(1) + "% ,正确率：" + Number(okRate * 100).toFixed(1) + "%");
    wx.hideLoading()
    // this.setData({
    //   errorSubjectList: errorSuject,
    //   okSubjectList: okSubject,
    //   errRateValue: Number(errRate * 100).toFixed(1),
    //   okRateValue: Number(okRate * 100).toFixed(1)
    // })

    this.setData({
      showModal: true,
      showResultTip: true,
      errorSubjectList: errorSuject,
      okSubjectList: okSubject,
      errRateValue: Number(errRate * 100).toFixed(1),
      okRateValue: Number(okRate * 100).toFixed(1),
      subjectList: subjectList,
      submitButtonShow: 'hidden'
    })
    // console.log("subjectList:%o:", this.data.subjectList)
  },
  dumpToSubject: function(event) {
    var suabjectPageIndex = event.currentTarget.dataset.subjectindex
    _closeBottomMistakeAnimation(this)
    this.setData({
      currentSubjectPageIndex: suabjectPageIndex
    })
  },
  findErrorSubjectList: function() {
    if (this.data.errorSubjectList.length > 0) {
      _openBottomMistakeAnimation(this)
    }
  },
  closeMistakeAnimation: function() {
    _closeBottomMistakeAnimation(this)
  },
  resultDialogOkClick: function() {
    this.setData({
      showModal: false
    })
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this
    var courseNo = options.courseId;
    var videoNo = options.videoId;
    var mTitle = options.title;
    var _isIOS = SystemInfoUtil.platform == SystemInfoUtil.IOS
    this.setData({
      isIOS: _isIOS
    })
    if (videoNo==null || wx.getStorageSync("userToken").length <= 0) {
      wx.reLaunch({
        url: '../login/login',
        success: function (res) { },
        fail: function (res) { },
        complete: function (res) { },
      })
      return
    }
    wx.setNavigationBarTitle({
      title: mTitle,
    })
    if (courseNo!=null&&typeof(courseNo)!=undefined){
      this.setData({
        currentVideoNo: videoNo,
        currentCourseNo: courseNo
      })
      this.data.courseFree = options.courseFree;
      this.data.courseBuyFlag = options.courseBuyFlag;
      this.loadVideoData(courseNo, videoNo)
    }else{
      this.setData({
        currentVideoNo: videoNo,
      })
      video.getVideoBaseInfo(videoNo, function (data) {
          that.setData({
            currentVideoNo: data.id
          })
        that.loadVideoData(data.id, videoNo)
      })
    }
    const res = wx.getSystemInfoSync()
    try {
      const res = wx.getSystemInfoSync()
      if (res.system.toLowerCase().indexOf('android') > -1) {
        this.data.isAndroid = true
      }
    } catch (e) {
      console.log(e)
    }
  },
  switchItem: function(event) {
    var that = this
    var mtype = event.currentTarget.dataset.mtype
    this._changeItemStatus(mtype)
    var currentTab = this.data.currentTab;
    if (currentTab === '0') { //纤细

    } else if (currentTab === '1') { //练习
      var videoUrl = this.data.currentVideoInfo.videoUrl + ""
      if (videoUrl.length <= 0) {
        this.buyVideo()
        return
      }
      if (this.data.hasSubject && this.data.subjectList.length <= 0) {
        video.getVideoSubjectList(this.data.currentVideoNo, function(list) {
          list.forEach(function(item, index) {
            item.option.forEach(function(opt, oIndex) {
              opt['selectStatus'] = 0
            })
          })
          list.sort(function(org1, org2) {
            return org2.option.length - org1.option.length
          });
          that.setData({
            subjectList: list
          })
          var _swiperHeight = (that.data.subjectItemHeight * list[0].option.length) + 200
          var query = wx.createSelectorQuery();
          query.select('#view-result-tip').boundingClientRect()
          query.exec(function(res) {
            //取高度
            if (res[0].height != undefined) {
              _swiperHeight += res[0].height
            }
            that.setData({
              swiperHeight: _swiperHeight
            })
          })
        })
      }
    }
  },
  _changeItemStatus(selectedIndex) {
    if (selectedIndex === '0') {
      this.setData({
        currentTab: selectedIndex,
        tuijian_text_color: color_selected,
        introduce_text_color: color_unselected
      })
    } else if (selectedIndex === '1') {
      this.setData({
        currentTab: selectedIndex,
        tuijian_text_color: color_unselected,
        introduce_text_color: color_selected
      })
    }
  },
  //播放绑定事件
  videoPlayHandle(e) {
    console.log('videoPlayHandle.e:%o', e)
    this.data.videoPlaying = true
    this.setData({
      controlHidden: false,
      multiListShow: false
    })
    this.videoContext.playbackRate(Number(this.data.currentRate))
    if (this.data.isSwitchDefinition) {
      console.log('seek')
      this.videoContext.seek(this.data.currentTime)
      this.data.isSwitchDefinition = false
    }

  },
  closeControl() {
    this.setData({
      multiListShow: false,
      rateShow: false
    })
  },
  buyVideo() {
    var that=this
    if(this.data.isIOS){
      //ios不支持
      wx.showModal({
        title: '温馨提示',
        content: "平台规则受限，IOS无法订阅该课程,更多消息请关注公众号，谢谢您的关注！",
        showCancel: false,
        confirmText:'好的'
      })
    }else{
      wx.showModal({
        title: '温馨提示',
        content: "支付 " + that.data.currentVideoInfo.price + "元 即可观看学习",
        cancelText: '不了',
        confirmText: '购买',
        success(res) {
          if (res.confirm) {
            wx.showActionSheet({
              itemList: ['微信支付', '粉币支付'],
              success: function (res) {
                if (res.tapIndex == 0) {
                  pay.getOrder("1012", "1003", that.data.currentVideoNo, "3001", null, function (success) {
                    var data = success.responseData
                    pay.pay(data.timeStamp, data.nonceStr, data.package, data.sign, function (state, res) {
                      if (state == 0) {
                        console.log("支付成功")
                        wx.showToast({
                          title: '支付成功',
                          icon: 'none',
                          duration: 3000
                        })
                        that.loadVideoData(that.data.currentCourseNo, that.data.currentVideoNo)
                      } else {
                        console.log("支付失败")
                        wx.showToast({
                          title: '支付失败',
                          icon: 'none'
                        })
                      }
                    })
                  })
                } else if (res.tapIndex == 1) {
                  pay.getOrder("1088", "1003", that.data.currentVideoNo, "3001", null, function (success) {
                    //success
                    wx.showToast({
                      title: '支付成功',
                      icon: 'none'
                    })
                    that.loadVideoData(that.data.currentCourseNo, that.data.currentVideoNo)
                  })
                }
              },
            })
            // video.getOrder("1003", that.data.currentVideoNo,"3001",function(payBean){
            //   console.log("微信支付与下单成功");
            //   var data = payBean.responseData
            //   video.buyVideo(data.timeStamp, data.nonceStr, data.package, data.sign,function(state,res){
            //     console.log("微信支付：%o", res);
            //     if (state==0){
            //       console.log("支付成功")
            //       that.loadVideoData(that.data.currentCourseNo,that.data.currentVideoNo)
            //     }else{
            //       console.log("支付失败")
            //     }
            //   })
            // })
          }
        }
      })
    }
  },
  //反馈
  goVideoFeedBack: function() {
    this.setData({
      optTip: '课堂反馈'
    })
    _openBottomAnimation(this)
  },
  //举报
  goVideoReport: function() {
    this.setData({
      optTip: '课堂举报'
    })
    _openBottomAnimation(this)
  },
  //反馈建议输入
  inputFeedBackText:function(event){
    this.setData({
      feedBackText: event.detail.value
    });
  },
  feedBackSubmit:function(event){
    var that=this;
    if (this.data.feedBackText.length<=0){
      wx.showToast({
        title: '请输入' + this.data.optTip+'内容',
        icon:null
      })
    }

    if (this.data.optTip.indexOf("举报")!=-1){
      feedBack.rePortVideo(this.data.currentVideoNo, this.data.feedBackText,function(s){
        _closeBottomAnimation(that)
        wx.showToast({
          title: "课堂举报成功",
          icon: null
        })
      })
    } else if (this.data.optTip.indexOf("反馈") != -1){
      feedBack.feedBackVideo(this.data.currentVideoNo, this.data.feedBackText,function(s){
        _closeBottomAnimation(that)
        wx.showToast({
          title: "课堂反馈成功",
          icon: null
        })
      })
    }
  },
  //播放器点击
  tapVideo(e) {
    try {
      var videoUrl = this.data.currentVideoInfo.videoUrl + ""
      if (videoUrl.length <= 0) {
        this.buyVideo()
        return
      }
      this.setData({
        multiListShow: false,
        rateShow: false,
      })
      console.log(this.data.videoPlaying)
      if (this.data.videoPlaying && !this.data.fullScreenData) {
        this.setData({
          controlHidden: !this.data.controlHidden
        })
      }
    } catch (e) {
      this.buyVideo()
    }
  },
  switchResource() {
    console.log('switch')
    this.setData({
      multiListShow: true
    })
  },
  showSwitchRate(rate) {
    this.setData({
      rateShow: true
    })
  },

  switchRate(e) {
    let dataset = e.currentTarget.dataset
    let {
      rate
    } = dataset
    console.log(this.data.videoplaying)
    if (this.data.videoplaying) {
      this.videoContext.playbackRate(Number(rate))
    }
    this.setData({
      currentRate: rate,
      rateShow: false
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    this.videoContext = wx.createVideoContext('videoPlayer')
  },
  //播放列表中其中一个
  tapPlay(e) {
    let vid = e.currentTarget.dataset['vid']
    this.playVideo(vid)
  },
  playVideo(vid) {
    if (!this.videoContext) {
      this.videoContext = wx.createVideoContext('videoPlayer')
    }
    // this.videoContext.stop()
    this.data.videoPlaying = false
    wx.showLoading({
      title: '加载中...',
      icon: 'none'
    })

  },
  //更新时间
  timeUpdate(e) {
    let {
      currentTime
    } = e.detail
    this.data.currentTime = currentTime
    this.data.videoplaying = true
  },
  //暂停
  playPaused() {
    this.data.videoplaying = false
  },
  //全屏
  fullScreen(e) {
    let {
      fullScreen,
      direction
    } = e.detail
    console.log(e)
    let fullScreenData = ""
    if (fullScreen) {
      fullScreenData = " full-screen " + direction
      this.setData({
        controlHidden: false
      })
    }
    console.log({
      fullScreen,
      direction
    })
    this.setData({
      fullScreenData
    })
    console.log(this.data.fullScreenData)
  },

  loadVideoData(courseId, videoId) {
    var that = this
    video.getVideoInfo(courseId, videoId, function(res) {
      res.duration = that.getVideoTime(res.duration)
      that.reSetPageData()
      that.setData({
        currentVideoInfo: res,
        currentVideoNo: videoId,
        currentCourseNo: courseId
      })
      if (res.isHaveSubject == 1) {
        that.setData({
          hasSubject: true
        })
      }
      video.getVideoListAndRemove(that.data.currentCourseNo, videoId, function(list) {
        that.setData({
          videoList: list
        })
      })
      if (res.isHaveSubject > 0) {
        //go to get subjectlist
        // video.getVideoSubjectList(videoId,function(list){
        //     that.setData({
        //       subjectList:list
        //     })
        // })
      }
    });
  },

  getVideoTime(duration) {
    let secondTotal = Math.round(duration);
    let hour = Math.floor(secondTotal / 3600);
    let minute = Math.floor((secondTotal - hour * 3600) / 60);
    let second = secondTotal - hour * 3600 - minute * 60;
    if (minute < 10) {
      minute = '0' + minute;
    }
    if (second < 10) {
      second = '0' + second;
    }
    return hour === 0 ? minute + ':' + second : hour + ':' + minute + ':' + second;
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },
  //相关视频点击
  onVideoItemClick: function(event) {
    var videoNo = event.detail.videoNo
    var position = event.detail.position
    var mTitle = event.detail.title
    wx.setNavigationBarTitle({
      title: mTitle,
    })
    this.loadVideoData(this.data.currentCourseNo, videoNo);
  },
  imageclick: function(event) {
    console.log('imageclick')
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    var shareObject = {
      title: this.data.currentVideoInfo.title + "【" + this.data.currentVideoInfo.remarks + "】",
      path: 'pages/video-info/video?courseId=' + this.data.currentCourseNo + "&title=" + this.data.currentVideoInfo.title + "&videoId=" + this.data.currentVideoNo + "&courseFree=" + this.data.courseFree + "&courseBuyFlag=" + this.data.courseBuyFlag,
      // imageUrl: this.data.courseDetailInfo.cover,
      success: function(res) {
        wx.showToast({
          title: '分享成功',
          icon: ''
        })
      }
    }
    return shareObject;
  },

  /**
   * 选择规格
   */
  selectedSpecifications: function(event) {
    console.log('selectedSpecifications')
    _openBottomAnimation(this)
  },
  closeAnimation: function(event) {
    _closeBottomAnimation(this)
  },

})

function _openBottomAnimation(context) {
  var animation = bottomAnimation
  context.animation = animation
  animation.translateY(-90 + 'vh').step()
  context.setData({
    animationData: animation.export(),
    bottomViewShow: true,
  })
}

function _openBottomMistakeAnimation(context) {
  var animation = bottomAnimation
  context.animation = animation
  animation.translateY(-90 + 'vh').step()
  context.setData({
    mistakeAnimationData: animation.export(),
    bottomMistakeViewShow: true,
  })
}

function _closeBottomAnimation(context) {
  var animation = bottomAnimation
  context.animation = animation
  animation.translateY(90 + 'vh').step()
  context.setData({
    animationData: animation.export(),
    bottomViewShow: false,
  })
}

function _closeBottomMistakeAnimation(context) {
  var animation = bottomAnimation
  context.animation = animation
  animation.translateY(90 + 'vh').step()
  context.setData({
    mistakeAnimationData: animation.export(),
    bottomMistakeViewShow: false,
  })
}

function cleanSpelChar(localData) {
  var noiseChar = "~!@#$%^&*()_+-=`[]{};':\"\\|,./<>?\n\r";
  var goodChar = "～！＠＃＄％＾＆＊（）＿＋－＝｀［］｛｝；＇：＂＼｜，．／＜＞？　　";
  for (var i = 0; i < noiseChar.length; i++) {
    var oneChar = noiseChar.charAt(i);
    var towChar = goodChar.charAt(i)
    while (localData.indexOf(oneChar) >= 0) {
      localData = localData.replace(oneChar, towChar)
    }
  }
  return localData;

}